package com.bookbuf.module;

import android.util.Log;

import com.bookbuf.module.exception.StubException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

/**
 * 模块管理器用于维护module实例。
 * author: robert.
 * date :  2016/12/26.
 */

public class ProxyManager {

    private static final String TAG = "ProxyManager";
    private static final HashMap<String, Proxy> map = new HashMap<>();

    public static Proxy newInstance(String module) throws StubException {
        Proxy m = null;
        synchronized (map) {
            if (map.containsKey(module)) {
                m = map.get(module);
                Log.i(TAG, "newInstance: get {" + module + "," + m.hashCode() + "}");
                return m;
            }
        }
        m = newModule(module);
        synchronized (map) {
            map.put(module, m);
            Log.i(TAG, "newInstance: put {" + module + "," + m.hashCode() + "}");
        }
        return newInstance(module);
    }

    private static Proxy newModule(String module) throws StubException {
        Class<?> clazz = null;
        try {
            clazz = Class.forName(module);
        } catch (ClassNotFoundException e) {
            throw new StubException(e.getMessage());
        }

        Constructor<?> constructor;
        try {
            constructor = clazz.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new StubException(e.getMessage());
        }
        if (constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return (Proxy) constructor.newInstance();
        } catch (InstantiationException e) {
            throw new StubException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new StubException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new StubException(e.getMessage());
        }
    }
}
